﻿Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports mshtml
'Imports mshtml
Imports SHDocVw


Public Class Form1

    <DllImport("winmm.dll")> _
    Public Shared Function waveOutGetVolume(h As IntPtr, ByRef dwVolume As UInteger) As Integer
    End Function

    <DllImport("winmm.dll")> _
    Public Shared Function waveOutSetVolume(h As IntPtr, dwVolume As UInteger) As Integer
    End Function

    Private waitTimer As New System.Windows.Forms.Timer()
    Private TimerTickHandler As EventHandler

    Sub New ()

        'WebBrowserUtils.SetWebBrowserFeatures(11)

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        me.webB1.AllowWebBrowserDrop = false

        Dim nativeBrowser = DirectCast(webB1.ActiveXInstance, SHDocVw.WebBrowser)

        AddHandler nativeBrowser.NewWindow2, AddressOf Form1_NewWindow2
        

        CheckForIllegalCrossThreadCalls = false
'        AddHandler nativeBrowser.NewWindow2, AddressOf DataChanged

        webB1.ScriptErrorsSuppressed = true
    

    End Sub


    
    Public  Property user As String
    Public Property  passwd As String 

    Public Property  LmtPro As integer

    Public Property  IFauto As integer

    ''' <summary>
    ''' 网页加载状态
    ''' </summary>
    ''' <returns></returns>
    public Property loading As Boolean

    ''' <summary>
    ''' 页面
    ''' </summary>
    ''' <returns></returns>
    Public  Property doc As System.Windows.Forms.HTMLDocument

'    public property docms As IHTMLDocument2



    Property Strlogin As String ="学员登录"

    Property Strstudy As String ="在线学习系统"

    Property Strstudysym As String ="进入学时管理系统"

    Property Strstudyonline As String ="进入在线学习系统"

    Property Strstudycenter As String ="学习中心"

    Property Strstudymycourse As String ="选择网络课程"
    Property Strstudycourse As String ="网络课程"

    Property strsearch as string ="查 询"

    property strchosecource as string ="choose_course"
'    Property StrUrl As String ="pro.learning.gov.cn"
    '5月15日发生url改动
    Property StrUrl As String ="learning.hzrs.hangzhou.gov.cn"
    
    Property StrUrlzw As String="zjzwfw.gov.cn"
    
    Property StrUrlGo As String ="study/login.php?act=go"

    Property StrUrlNetCourse As String =StrUrl + "/my/choose_course.php"
'    Property StrUrlNetCourse As String =StrUrl + "/course.php"
'    Property StrUrlNetCourse As String =StrUrl + "/my/"
    Property StrUrlCourse As String ="course"
    Property StrUrlNetstudytime As String =StrUrl + "/study/"


    Property strbtn As String ="button"

    Property stra As String ="a"

    Property strli As String ="li"

    Property strdiv As String ="div"
    Property strp As String ="p"

   
    Property users As New list(Of  UserInfo)()

    Property lastuser As New UserInfo

    Property waittime  As Boolean


    ''' <summary>
    ''' 需求总学时
    ''' </summary>
    ''' <returns></returns>
    Property tolScoreReq As Double

    ''' <summary>
    ''' 需求专业学时
    ''' </summary>
    ''' <returns></returns>
    Property proScoreReq As Double

    ''' <summary>
    ''' 需求公需学时
    ''' </summary>
    ''' <returns></returns>
    Property norScoreReq As Double


    ''' <summary>
    ''' 已获得总学时
    ''' </summary>
    ''' <returns></returns>
    Property tolScoreGain As Double

    ''' <summary>
    ''' 已获得专业学时
    ''' </summary>
    ''' <returns></returns>
    Property proScoreGain As Double

    ''' <summary>
    ''' 已获得公需学时
    ''' </summary>
    ''' <returns></returns>
    Property norScoreGain As Double

    ''' <summary>
    ''' 课程学分余量
    ''' </summary>
    ''' <returns></returns>
    Property Scoreoffset As Double=10.0
'    Property Scoreoffset As Double=552.0

    ''' <summary>
    ''' 课程实际时长
    ''' </summary>
    ''' <returns></returns>
    Property selCourseTime As Double=5.0

    Property lstcourse As new List(Of course)


    Property frm as Form2

    Property courseord as Integer=0

    Property coursenum as Integer=20

    Public Property csStartTime As System.DateTime
    Public Property csEndTime As System.DateTime
    Public Property csts As System.TimeSpan

    ''' <summary>
    ''' load计时器
    ''' </summary>
    ''' <returns></returns>
    Public Property LoadTimer As Timer
    ''' <summary>
    ''' load计时器是否在运行
    ''' </summary>
    ''' <returns></returns>
    Public Property IsLoadTimerRun As Boolean = false

    ''' <summary>
    ''' load计时器间隔
    ''' </summary>
    ''' <returns></returns>
    Public Property LoadTimerLimit As  double =5

    ''' <summary>
    ''' load计时器间隔2
    ''' </summary>
    ''' <returns></returns>
    Public Property LoadTimerLimit2 As  double =10

    ''' <summary>
    ''' 点击延迟
    ''' </summary>
    ''' <returns></returns>
    Public Property delayseconds As  double =2000


    ''' <summary>
    ''' 计时器
    ''' </summary>
    ''' <returns></returns>
    Public Property objTimer As Timer
    ''' <summary>
    ''' 计时器是否在运行
    ''' </summary>
    ''' <returns></returns>
    Public Property IsTimerRun As Boolean = false
    ''' <summary>
    ''' 播放时间间隔
    ''' </summary>
    ''' <returns></returns>
    Public Property playtime as double =12

    ''' <summary>
    ''' 异步消息更新
    ''' </summary>
    ''' <param name="message"></param>
    public delegate sub UpdateText(message As string)


    Public Property msStartTime As System.DateTime
    Public Property msEndTime As System.DateTime

    Public Property msts As System.TimeSpan
    ''' <summary>
    ''' 学习页码
    ''' </summary>
    ''' <returns></returns>
    Public Property learnpage As Integer = 1


    Public Property LastUrl As String
        get 
            return _LastUrl
        End Get
        Set(value As String)
            _LastUrl=value
        End Set
    End Property

    private Property _LastUrl As String

    public Property Clickelm As HtmlElement
    ''' <summary>
    ''' 是否成功程璐
    ''' </summary>
    ''' <returns></returns>
    public Property IsSusLogin As Boolean = false

    ''' <summary>
    ''' 是否project course
    ''' </summary>
    ''' <returns></returns>
    public Property IsProcourse As Boolean = false

    ''' <summary>
    ''' 是否存在专业课程
    ''' </summary>
    ''' <returns></returns>
    public Property IsProcourseExist As Boolean = true
    ''' <summary>
    ''' 是否存在公需课程
    ''' </summary>
    ''' <returns></returns>
    public Property IsNorcourseExist As Boolean = true

    ''' <summary>
    ''' 是否初始化中
    ''' </summary>
    ''' <returns></returns>
    public Property IsInital As Boolean = true



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

'        PW.OpenPw()
'        users=pw.Users

        Dim _savedVolume As UInteger

        waveOutGetVolume(IntPtr.Zero, _savedVolume)
        ' restore the volume upon exit
        '        Me.FormClosing += Sub() waveOutSetVolume(IntPtr.Zero, _savedVolume)

        ' mute
        waveOutSetVolume(IntPtr.Zero, 0)



        TsbOrd.Text=0
        ToolStripButton1_Click(nothing,nothing)
    End Sub





    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click

        WebB1.Navigate(StrUrl)

    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
       

'        Dim Clickelm As HtmlElement

        PW.OpenPw()
        users=pw.Users
        lastuser=pw.LastUser

        Dim up As New Form_userpass(users,lastuser)

        If up.ShowDialog(Me)=DialogResult.OK Then
            user=up.CbxUsername.Text
            passwd=up.TbxPassword.Text
            If IsNumeric(up.TbxProLimit.Text) Then
                LmtPro=CInt(up.TbxProLimit.Text)
            Else 
                LmtPro=0
            End If 
            if LmtPro=0 Then
                LmtPro=99999
            End If
            If up.CheckBox1.Checked=True Then
                IFauto=1
            Else 
                IFauto=0
            end if


'            '调试代码
'            user="13806520"
'            passwd="1234"
            '调试代码结束

        End If
        '获得用户名账号
        If user="" Or passwd ="" Then
                MessageBox.Show("用户名为空或者密码为空，请检查","错误")
                up.Dispose()
                Exit Sub
        Else 
            
            doc = webB1.Document

            if loginorfresh()=False then
                exit sub
            End If
            Readdata()
            readcourse()

'            Dim tables  as  IHTMLElementCollection= docms.all.tags("TABLE")
'            Dim table as IHTMLTable=tables(0)
'
'            dim rows = table.rows
'            dim ms as string =""

'            For Each r As IHTMLElement In rows
'                
'                For each c as IHTMLElement in r.children
'                    ms+= c.innerText.ToString()+vbtab
'                Next
'                ms+=vbCrLf
'               
'            Next

'            MessageBox.Show(ms)

'            MessageBox.Show("已登陆学习界面")

        End If

       



    End Sub
    ''' <summary>
    ''' 启动登陆页面
    ''' </summary>
    Private function loginorfresh() As boolean

            if IFauto=1 Then
                StartTimer(playtime)
            End If
            
            IsSusLogin=false
            Dim urlnew As String
            dim cnum as Integer =0
            Dim climit as Integer =7
            Dim  Iffirst =true
            '未进入
Login:      While ((WebB1.url.ToString().Contains(StrUrl) and ClickElmExist(Strstudysym ,strbtn))=false andalso cnum<climit)

                urlnew =WebB1.url.ToString()
                '如果需要登陆
                If urlnew.Contains(StrUrl) Then

                                    '如果打开的是学习网站，需要选择
                    If urlnew.Contains(StrUrlGo) Then
                        If ClickElmExist(Strstudy ,stra) Then
                            Clickbutton(ClickElm)
                        End If

                    elseif ClickElmExist(Strlogin,strbtn) Then
                        ClickbuttonLogin()
                    End If
                End If


                '如果打开的是政务网跳转则登陆
                If urlnew.Contains(StrUrlzw) Then
                   
                    dim kkk As Integer = 5
                    dim ktime As Integer =0

                 '   MessageBox.Show(ktime)

                   loading =false
'                   Thread.SpinWait(5000
'                   Thread.sleep(5000)
                    Wait(500,  Sub() Nonthing() )
                    While waittime = False
                        Application.DoEvents()
                    End While
                    loading =true

     '              if IFauto=1 Then
     '                  LoadTimerStart(LoadTimerLimit2)
     '                  doc.GetElementById("account_login_identifier").Focus()
     '                  SendKeys.SendWait("^a")
     '                  SendKeys.SendWait("{DEL}")
     '                  SendKeys.SendWait(user)
     '                  doc.GetElementById("account_login_password").Focus()
     '                  SendKeys.SendWait("^a")
     '                  SendKeys.SendWait("{DEL}")
     '                  SendKeys.SendWait(passwd)
     '                  SendKeys.SendWait("{ENTER}")    
'    '               loading =true
     '              ElseIf Iffirst =True Then
     '                  doc.GetElementById("account_login_identifier").Focus()
     '                  SendKeys.SendWait("^a")
     '                  SendKeys.SendWait("{DEL}")
     '                  SendKeys.SendWait(user)
     '                  doc.GetElementById("account_login_password").Focus()
     '                  SendKeys.SendWait("^a")
     '                  SendKeys.SendWait("{DEL}")
     '                  SendKeys.SendWait(passwd)
     '                  SendKeys.SendWait("{ENTER}")
     '                 Iffirst =FALSE
     '
     '              End If
                    


'                    doc.GetElementById("loginpwd").Focus()
'                    dim form =doc.Forms("uspForm")
'                    form.InvokeMember("submit")
'                    dim sumb = doc.GetElementById("submit")
'                    sumb.InvokeMember("click")

'                    SendKeys.SendWait("{ENTER}")

                 waitturninto()

                End if

                cnum +=1
           
             End While
            
'            '判断跳转是否已经登陆，否则再来一次
'            If ClickElmExist(Strstudysym ,strbtn) Then
'                goto Login
'            End If


            if cnum>= climit Then
                MessageBox.Show("登陆或者进入网页失败，检查程序")
                return false
            End If

'            '判断跳转是否已经登陆，否则再来一次
'            If ClickElmExist(Strlogin ,strbtn) Then
'                Goto login
'
'            End If

                ' 查找ID为txtCSRQ的元素
'           '保存登录账户
            pw.RecordLastPw(user,passwd,LmtPro,IFauto)
            pw.SavePw(user,passwd,LmtPro,IFauto)
            
            IsSusLogin=true
            if IFauto=1 Then
                closetimer()
            End If
           

            texthis("已经成功登录"+user+"账户")
            return true
        end function
    Private sub Readdata()

        ’判定是否需要登陆，可能刷新时出错
        Dim urlnew =WebB1.url.ToString()
        If urlnew.Contains(StrUrlGo) or  urlnew.Contains(StrUrlzw) Then
            if loginorfresh()=False then
                exit sub
            End If
        End If

        msStartTime=Now

        '进入学时管理系统，读取已学习和学时要求
        If ClickElmExist(Strstudysym ,strbtn) Then
                Clickbutton(ClickElm)
        End If
        loading =true
        WebB1.Navigate(StrUrlNetstudytime)
        waitturninto()
        Thread.Sleep(500)
        getscore()

'            '进入主页
'        If ClickElmExist(Strstudyonline ,strdiv) Then
'                Clickbutton(ClickElm)
'        End If
'        Thread.Sleep(delayseconds)
'
'            ’进入学习中心
'        If ClickElmExist(Strstudycenter ,stra) Then
'            Clickbutton(ClickElm)
'        End If
'
'        Thread.Sleep(delayseconds)
'
'            ’进入选择网络课程
'        If ClickElmExist(Strstudymycourse ,strbtn) Then
'            Clickbutton(ClickElm)
'        End If

        ’进入选择网络课程
        loading =true


        WebB1.Navigate(StrUrlNetCourse)
        waitturninto()

'        Thread.Sleep(500)

        texthis("已经进入课程选择")

        END Sub
    Private sub readcourse()

            ‘判断是否要学习专业课程
'        Dim procousernum as Double
        Dim urlnew =WebB1.url.ToString()
        If Not(urlnew.Contains(StrUrlCourse)) Then 
            loading=true
            WebB1.Navigate(StrUrlNetCourse)
            waitturninto()

'            Thread.Sleep(delayseconds)
        End If


        if learnpage >1 then
            ‘退出学习

'            dim msgs as String ="已经学完20节课程，停止学习，请重新点击登陆后再继续学习"
            dim msgs as String ="已经学完20节课程，继续学习"

'            MessageBox.Show(msgs)
            texthis(msgs)
'            frm.Close()
            msgs  ="关闭其他窗口，请重新登陆继续学习"
            texthis(msgs)

            TsbStop_Click(Nothing,nothing)
            Exit Sub
'
''            ’进入学习中心
'            If ClickElmExist(Strstudycenter ,stra) Then
'                Clickbutton(ClickElm)
'            End If
''
''            ’进入选择网络课程
'            If ClickElmExist(Strstudymycourse ,strbtn) Then
'                Clickbutton(ClickElm)
'            End If


        End If





' re:      If proScoreGain < proScoreReq+Scoreoffset And IsProcourseExist=True then
        '考试类型
        dim exam = doc.GetElementById("examtype")
        exam.SetAttribute("value", “W”)

re:      If proScoreGain < (LmtPro+Scoreoffset) And IsProcourseExist=True then
                '进行专业课程学习
            dim aa = doc.GetElementById("coursetype")
            doc.GetElementById("coursetype").SetAttribute("value", “15”)
            If ClickElmExist(strsearch,strbtn) Then
'                Clickbutton(ClickElm)
                Clickbutton(ClickElm)
            End If
            IsProcourse=True


        Else 
                    ‘进行公需学习
            doc.GetElementById("coursetype").SetAttribute("value", “17”)
            If ClickElmExist(strsearch,strbtn) Then
                Clickbutton(ClickElm)
            End If
            IsProcourse=false

        End If



'            docms = DirectCast(webB1.Document.DomDocument, IHTMLDocument2)

        dim table =doc.GetElementsByTagName("table")

        lstcourse.Clear()

        Try
            dim trcol = table(0).GetElementsByTagName("tr")

            For i = 0 To trcol.Count - 1
                dim row = trcol(i).GetElementsByTagName("td")
                if row.Count <> 0 then
'                    dim rowLL1=DirectCast(row(1).DomElement, IHTMLElement)
'                    dim a = rowLL1.getAttribute("type")
                    dim ab = row(1).InnerHtml.Split(chr(34))
                    dim d = ab(ab.Count()-2)
                    lstcourse.Add(new course(row(0).InnerText, row(2).InnerText, d.ToString(),row(3).InnerText,
                                             row(4).InnerText, row(5).InnerText, row(7).InnerText, row(6).InnerText))

                End If
            Next



        Catch ex As Exception

            IsProcourseExist =False

        End Try
   
        coursenum=lstcourse.Count
        IsInital=false
        If lstcourse.Count>0 Then 
            If IsProcourse then

                IsProcourseExist =true
            Else
                IsnorcourseExist =true
            End If
        else
            If IsProcourse then
                IsProcourseExist =false
                goto re
            Else
                IsnorcourseExist =false
            End If    

        End If
        
        
        tsbord.Text=0

        texthis("已经获取一页学习课程信息")



    End Sub
    ''' <summary>
    ''' 刷新
    ''' </summary>
    Private sub webrefresh()

        webB1.Document.ExecCommand("Refresh",false,nothing)

    End sub
   
    Private Sub WebB1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebB1.DocumentCompleted
        if webB1.ReadyState < WebBrowserReadyState.Complete Or webB1.Url.ToString() = LastUrl then return
        '自动点击弹出确认或弹出提示
        Dim vDocument As IHTMLDocument2 = DirectCast(webB1.Document.DomDocument, IHTMLDocument2)
        vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript")
        '弹出确认
        vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript")
        '弹出提示

        LastUrl = webB1.Url.ToString()

        loading = false
    

'        webB1.ScriptErrorsSuppressed = true
    End Sub

    Private Sub  HandleDocumentCompletedEvent(sender As Object, e As WebBrowserDocumentCompletedEventArgs)  
        if webB1.ReadyState < WebBrowserReadyState.Complete Or webB1.Url.ToString() = LastUrl then return
        LastUrl = webB1.Url.ToString()

        Clickelm.InvokeMember("click")

    End Sub

    Private Sub waitturninto()

        
        While(loading=true)

            Application.DoEvents()

        End While

    End Sub

    Private sub Clickbutton(ByRef elm As HtmlElement) 
'        If ClickElmExist(Strlogin,strbtn) Then

        loading =true
        LoadTimerStart(LoadTimerLimit)
        elm.InvokeMember("click")
        waitturninto()
      
    End sub

        Private sub ClickbuttonWait(ByRef elm As HtmlElement) 
'        If ClickElmExist(Strlogin,strbtn) Then

        loading =true
'        LoadTimerStart(LoadTimerLimit)
        elm.InvokeMember("click")
        
      
    End sub


    Private sub ClickbuttonNew(ByRef elm As HtmlElement) 
'        If ClickElmExist(Strlogin,strbtn) Then

        elm.InvokeMember("click")

    End sub


    Private function ClickbuttonLogin() As Boolean
'        If ClickElmExist(Strlogin,strbtn) Then

        loading =true
        LoadTimerStart(LoadTimerLimit)
        Clickelm.InvokeMember("click")
        waitturninto()
        Return true

'        Else
'            MessageBox.Show("未找到登录口，请检查网页")
'            Return false
'        End If

    End function

    Private function ClickElmExist(ByVal intext As string,ByVal elmstring As string) As Boolean


        Dim element2 As System.Windows.Forms.HtmlElementCollection = doc.GetElementsByTagName(elmstring)

        For Each elm As HtmlElement In element2
            If elm.InnerText =intext  Then
                Clickelm=elm
                Return true
            End If
        Next

        Return false
        

    End Function
    Private function ClickElmExist(ByVal intext As string,ByVal elmstring As string,Byval vid As string) As Boolean

        Dim element2 As System.Windows.Forms.HtmlElementCollection = doc.GetElementsByTagName(elmstring)

        For Each elm As HtmlElement In element2


            If elm.InnerText =intext Then
                dim ab = elm.outerHtml.Split(chr(34)).ToList()
                dim intd=ab.Findindex(Function(a) a.Contains("href="))
                if intd>0 Then
                    if ab(intd+1).EndsWith(vid) Then
                        Clickelm=elm
                        Return true
                    end if
                End If
  

            End If
        Next 

        Return false
        

    End Function
   

    ''' <summary>
    ''' 获取学时要求和已获得学时
    ''' </summary>
    sub getscore()
        
            If ClickElmExist("年度学时要求",strdiv) Then

                Dim elmcol=ClickElm.Parent.GetElementsByTagName(strp)
                For Each elm as HtmlElement In elmcol
                    Dim intxt =elm.Innertext

                    Select Case intxt.First()

                        Case "本"
                            dim pt = intxt.Split("学时",10,StringSplitOptions.RemoveEmptyEntries)
                            If Not IsNumeric(pt.Last()) Then
                                tolScoreReq= CDbl(pt(pt.Count-2))
                            Else 
                                tolScoreReq=CDbl(pt.Last())
                            End If
'                            tolScoreReq= CDbl(pt(pt.Count-1))
                        Case "专"
                            dim pti =intxt.IndexOf("程",StringComparison.CurrentCulture)
                            dim pt =intxt.Substring(pti +1,intxt.IndexOf("学时",StringComparison.CurrentCulture)-pti-1)
                            proScoreReq= CDbl(pt)
                        Case "不"
                            dim pti =intxt.IndexOf("于",StringComparison.CurrentCulture)
                            dim pt =intxt.Substring(pti +1,intxt.IndexOf("学时",StringComparison.CurrentCulture)-pti-1)
                            norScoreReq= CDbl(pt)

                    End Select

                Next


            End If

            If ClickElmExist("现已完成学时",strdiv) Then
                Dim elmcol=ClickElm.Parent.GetElementsByTagName(strp)
                For Each elm as HtmlElement In elmcol
                    Dim intxt =elm.Innertext

                    Select Case intxt.First()

                        Case "现"
                            dim pti =intxt.IndexOf("计",StringComparison.CurrentCulture)
                            dim pt =intxt.Substring(pti +1,intxt.IndexOf("学时",StringComparison.CurrentCulture)-pti-1)
                            proScoreGain= CDbl(pt)
                        Case "专"
                            dim pti =intxt.IndexOf("程",StringComparison.CurrentCulture)
                            dim pt =intxt.Substring(pti +1,intxt.IndexOf("学时",StringComparison.CurrentCulture)-pti-1)
                            proScoreGain= CDbl(pt)
                        Case "一"
                            dim pti =intxt.IndexOf("需",StringComparison.CurrentCulture)
                            dim pt =intxt.Substring(pti +1,intxt.IndexOf("学时",StringComparison.CurrentCulture)-pti-1)
                            norScoreGain= CDbl(pt)

                    End Select

                Next




            End If

        texthis("已经获取学时信息")
        texthis("已经获得专业学时：" & proScoreGain & vbTab & "公需学时：" & norScoreGain & vbTab & "总学时：" & tolScoreGain )
  

    End sub

    Private Sub WebB1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles WebB1.Navigated
        '自动点击弹出确认或弹出提示
        Dim vDocument As IHTMLDocument2 = DirectCast(webB1.Document.DomDocument, IHTMLDocument2)
        vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript")
        '弹出确认
        vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript")
        '弹出提示
    End Sub


    private sub learncourse(ByRef selcourse As course)
        '点击课程，修改在本页内打开
        if ClickElmExist(selcourse.coursename,stra,selcourse.courseid) then
'            Clickelm.SetAttribute("target","_self")
            Clickbuttonnew(ClickElm)
            texthis("开始学习课程"+selcourse.tostring())
        End If

        '打开后获取视频时间

       

    End sub

    Private Sub WebB1_NewWindow(sender As Object, e As CancelEventArgs) Handles WebB1.NewWindow
'        Messagebox.show("正在打开")
'        dim frm = new Form2()
'
'        frm.webBrowser1.Navigate(webB1.StatusText)
'        e.Cancel = true
'        frm.show()


    End Sub

    Private Sub Form1_NewWindow2(ByRef ppDisp As Object, ByRef Cancel As Boolean)
        frm=new form2()
        '事先建好一个带WebBrowser的窗体
        ppDisp = frm.webBrowser1.ActiveXInstance

        AddHandler frm.DataChange, Addressof DataChanged
        texthis("已经成功新建课程页面")
        frm.Text="信息窗口"
        frm.Show()
        frm.Visible = False

    End Sub

    Private Sub Form1_NewWindow3(ByRef ppDisp As Object, ByRef Cancel As Boolean, dwFlags As UInteger, bstrUrlContext As String, bstrUrl As String)
        Cancel = True
        Me.webB1.Navigate(bstrUrl)
    End Sub

    Private Sub TsbStartlearn_Click(sender As Object, e As EventArgs) Handles TsbStartlearn.Click
        ’学习过程
        courseord=Cint(tsbord.Text)
        ‘调试用
'        If courseord=0 then
'            courseord=19
'            tsbord.Text=20
'        End If
'        courseord=19

        ‘调试用结束

        If lstcourse.Count>0 Then
            csStartTime = System.DateTime.Now
            learncourse(lstcourse(courseord))
            
        Else 
            texthis("已经学完全部课程，如有课程在选课列表中，请删除后重新开始学习")

        End If


    End Sub

   ‘数据变化事件
    public sub DataChanged(sender As Object, args As DataChangeEventArgs )

        '更新窗体控件
        if args.name=("closed") then
            csEndTime = System.DateTime.Now
            csts =csEndTime.Subtract(csStartTime)

            if csts.TotalSeconds<60 Then
                texthis("未学习完成课程，间隔时间"+csts.Seconds.ToString()+"秒")
            else
                courseord +=1
                texthis("已经成功学习完成课程，子窗口已关闭")
                tsbord.Text=courseord
                
              
            End If

        elseif args.name=("msg") then
            texthis(args.pass)


        End If

    end sub


    '数据变化继续学习
    Private Sub TsbOrd_TextChanged(sender As Object, e As EventArgs) Handles TsbOrd.TextChanged

        courseord=Cint(tsbord.Text)

        
        If IsInital then
            exit sub
        End If

        If IsnorcourseExist = False Then
            texthis("公需课程已没有，检查是否学完全部课程，如有课程在选课列表中，请删除后重新开始学习")
            exit sub
        End If

        If IsProcourseExist = False and coursenum = 0 Then
            texthis("专业课程已学完，进入公需课程学习")
            readcourse()
            tsbord.Text=0
        End If


        if courseord<coursenum and courseord<>0 Then
            
            TsbStartlearn_Click(Nothing,nothing)

        elseif courseord>=coursenum then
            '如果大于则重新刷新页面继续学习
'            Readdata()

'            Readdata()
'            webrefresh()
            learnpage+=1
            readcourse()
            tsbord.Text=0


        Else 
            courseord=0 


        End If

    End Sub

    ''' <summary>
    ''' 日志和显示历史消息
    ''' </summary>
    ''' <param name="msg"></param>
    Private Sub texthis(byval msg As string)
        dim tim = DateTime.Now.tostring("yyyy-MM-dd HH:mm:ss")
        dim ms = tim & vbTab & vbTab & msg & vbCrLf 


        log.WriteLog(ms)

'        RtbHis.SelectionStart = RtbHis.Text.Length
        If Not ms.StartsWith("已经学完20节课程") Then
            RtbHis.Text=ms+RtbHis.Text
        End If
        

'        RtbHis.Text+=ms
        
'        msEndTime =Now
'        msts =msEndTime.Subtract(msStartTime)
'
'        if msts.TotalSeconds>5  then
'
'            RtbHis.SelectionStart = RtbHis.Text.Length
'            RtbHis.ScrollToCaret()
'            msStartTime=Now
'        End If
'        
        
        

    End Sub

    Private Sub TsbStop_Click(sender As Object, e As EventArgs) Handles TsbStop.Click

        if e isnot nothing Then
            texthis("用户停止学习")
        End If
        

        frm.Close()
        
    End Sub

    Public Sub LoadTimerStart(ByVal timedelay As double)    

        Dim tcb As New TimerCallback(AddressOf Me.LoadTimerMethod)    
'        Dim objTimer As Timer
        
        LoadTimer = New Timer(tcb, Nothing,TimeSpan.Fromseconds(timedelay),TimeSpan.Fromseconds(timedelay))  

        IsloadTimerRun=True

    End Sub    

    Public Sub LoadTimerMethod(ByVal state As Object)
        ‘定时器，检查时间，如果已经到达计时则关闭子窗口
'        MsgBox("The Timer invoked this method.")  

        loading = false

        CloseLoadTimer()
'        if IsSusLogin=false then
'            if loginorfresh()=False then
'                exit sub
'            End If
''            loginorfresh()
'        End If

    End Sub 

    Public Sub CloseLoadTimer()    
'
'        Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)    
''        Dim objTimer As Timer
        
        LoadTimer.Dispose()
        IsLoadTimerRun=false

    End Sub 






    Public Sub StartTimer(ByVal timedelay As double)    

        Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)    
'        Dim objTimer As Timer
        
        objTimer = New Timer(tcb, Nothing,TimeSpan.Fromseconds(timedelay),TimeSpan.Fromseconds(timedelay))  
        IsTimerRun=True

    End Sub    
    Public Sub TimerMethod(ByVal state As Object)
        ‘定时器，检查时间，如果已经到达计时则关闭子窗口
'        MsgBox("The Timer invoked this method.")  

        if IsSusLogin=false then
            '若时间间隔到了，已经开启页面未关闭，则强制关闭页面
'            doc= New System.Windows.Forms.HtmlDocument()
'            doc = webB1.Document
'            ToolStripButton1_Click(Nothing,Nothing)
'            MessageBox.Show(WebB1.Url.ToString())
            if loginorfresh()=False then
                exit sub
            End If
'            loginorfresh()
        End If

    End Sub 
    Public Sub CloseTimer()    
'
'        Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)    
''        Dim objTimer As Timer
        
        objTimer.Dispose()
        IsTimerRun=false

    End Sub  
    Private Sub Wait(delay As Integer, action As Action)
        waitTimer.Interval = delay
        TimerTickHandler = New EventHandler(
            Sub()
                action.Invoke()
                waitTimer.Stop()
                RemoveHandler waitTimer.Tick, TimerTickHandler
            End Sub)
        AddHandler waitTimer.Tick, TimerTickHandler
        waitTimer.Start()
    End Sub

    Private Sub Nonthing()

        Dim non="dddd"
        Console.Write(non)
        waittime=true

    End Sub



End Class
